<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\common\controller;

use think\facade\Validate;

class ContentController extends AdminController
{
    public $modelId = 0;

    public function __construct($controllerName = '',$modelId = 0)
    {
        $this->controllerName = $controllerName;
        $this->modelId = $modelId;

        parent::__construct();
    }

    public function initialize(){
        $this->modelName = 'Content';
        parent::initialize();
        $this->assign('model_id',$this->modelId);
    }

    /**
     * 模型分类列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function category(){
        $categoryModelName = 'Category';

        $this->assign('controllerName',$this->controllerName . '分类');

        $aorm = model($categoryModelName);
        /**
         * 查询条件
         */
        $whereKeys = $aorm->getSearchFields();

        $alj = new \app\common\logic\AdminLogic($categoryModelName);
        $paramWhere = $this->getParamWhere($whereKeys);
        // 外加搜索条件
        $paramWhere['where'][] = ['model_id','=',$this->modelId];
        // TODO: 小区（项目） 附加查询
        $paramWhere['where'][] = ['project_id','=',$this->getProjectId()];

//        $pagerInfo = $this->getPagerInfo($alj->_getCountByWhere($paramWhere['where']),input('p',1),$paramWhere['search'],9999);
        $dataList = $alj->_getListByWhere($paramWhere['where']);

        // 处理属性显示
        $dataList = getSortedCategory($dataList);

        $this->assign('datas', $dataList);
        return $this->fetch('common/base_content_category_index');
    }

    /**
     * 分类添加的时候 处理需要显示的表单
     * @param $formFields
     * @return array
     */
//    protected function handleCategoryAddFormFields(&$formFields){
//        return ['err_code' => 0 , 'msg' => '默认通过'];
//    }
    public function category_add(){
        $param = input('param.');

        $categoryModelName = 'Category';
        $this->assign('controllerName',$this->controllerName . '分类');

        $orm = model($categoryModelName);
        $formFields = $orm->getAddFields();
//        dump($formFields);exit;
        if (request()->isAjax()){
            if(empty($param['id'])){
                $param['id'] = 0;
            }
            $param['project_id'] = $this->getProjectId();
            $alj = new \app\common\logic\AdminLogic($categoryModelName);
            // 按数据库里面定制的来进行验证
            foreach ($formFields as $field){
                if(!empty($field['validate'])){
                    if(is_array($field['validate'])){
                        // 去掉不需要验证的
                        foreach ($field['validate'] as $key => $item){
                            if(empty($item)){
                                unset($field['validate'][$key]);
                            }
                        }
                    }
                    if(is_string($field['validate'])){
                        $validate = Validate::make([
                            $field['name']  => $field['validate'],
                        ]);
                        if (!$validate->check($param)) {
                            $this->error($field['text'] . ' ' . getValidateErrorText($field['validate']));
                        }
                    }
                }
            }

            $flag = $alj->save($param);
            if($flag['err_code'] === 0){
                $this->success($flag['msg'].',返回列表页',url('category'));
            }
            else{
                $this->error($flag['msg']);
            }
        }

        $formFields['parent_id']['type'] = 'select_source';
        $formFields['parent_id']['type_value_custom']['source'] = 'catList';

        $cLogic = new \app\common\logic\ContentLogic();
        $where[] = ['model_id','=',$this->modelId];
        $data = $cLogic->_getCategorySelectData($where);
        $this->addSelectList('catList',$data);
        // 不显示 链接地址
        unset($formFields['url']);

        // aop
        if(method_exists($this,'handleCategoryAddFormFields')){
            $jieguo = $this->handleCategoryAddFormFields($formFields);
            if($jieguo['err_code'] !== 0){
                $this->error($jieguo['msg']);
            }
        }

        $this->assign('modelId',$this->modelId);
        $this->assign('formFields',$formFields);
        // 通过数据源设置的变量
        $this->assign('selectList',$this->getSelectList());

        return $this->fetch('common/base_content_category_add');
    }

    /**
     * 分类编辑的时候 处理需要显示的表单
     * @param $formFields
     * @return array
     */
//    protected function handleCategoryEditFormFields(&$formFields){
//        return ['err_code' => 0 , 'msg' => '默认通过'];
//    }
    public function category_edit(){
        $param = input('param.');

        $categoryModelName = 'Category';
        $this->assign('controllerName',$this->controllerName . '分类');

        $alj = new \app\common\logic\AdminLogic($categoryModelName);

        $orm = model($categoryModelName);
        $formFields = $orm->getEditFields();
        if (request()->isAjax()){
            if(empty($param['id'])){
                $this->error('id参数错误');
            }
            $param['id'] = hashIdDecode($param['id']);
            if(empty($param['id'])){
                $this->error('id参数错误');
            }
            // 按数据库里面定制的来进行验证
            foreach ($formFields as $field){
                if(!empty($field['validate'])){
                    if(is_array($field['validate'])){
                        // 去掉不需要验证的
                        foreach ($field['validate'] as $key => $item){
                            if(empty($item)){
                                unset($field['validate'][$key]);
                            }
                        }
                    }
                    if(is_string($field['validate'])){
                        $validate = Validate::make([
                            $field['name']  => $field['validate'],
                        ]);
                        if (!$validate->check($param)) {
                            $this->error($field['text'] . ' ' . getValidateErrorText($field['validate']));
                        }
                    }
                }
            }

            $flag = $alj->save($param);
            if($flag['err_code']  === 0){
                $this->success($flag['msg'] . '，返回列表',url('category'));
            }
            else{
                $this->error($flag['msg']);
            }
        }

        $id = input('param.id');
        if (empty($id)){
            $this->error('参数错误',url('index'));
        }
        $id = hashIdDecode($id);
        if (empty($id)){
            $this->error('参数错误',url('index'));
        }
        $this->assign('formFields',$formFields);

        $chaxun = $alj->getModelByPk($id);
        if($chaxun['err_code'] !== 0){
            return json($chaxun);
        }
        $model = $chaxun['data'];
        $pkName = db($categoryModelName)->getPk();
        $model[$pkName] = hashIdEncode($model[$pkName]);
        $this->assign([
            'model' => $model,
        ]);

        $formFields['parent_id']['type'] = 'select_source';
        $formFields['parent_id']['type_value_custom']['source'] = 'catList';

        $cLogic = new \app\common\logic\ContentLogic();
        $where[] = ['model_id','=',$this->modelId];
        $data = $cLogic->_getCategorySelectData($where);
        $this->addSelectList('catList',$data);
        // 不显示 链接地址
        unset($formFields['url']);

        // aop
        if(method_exists($this,'handleCategoryEditFormFields')){
            $jieguo = $this->handleCategoryEditFormFields($formFields);
            if($jieguo['err_code'] !== 0){
                $this->error($jieguo['msg']);
            }
        }

        $this->assign('modelId',$this->modelId);
        $this->assign('formFields',$formFields);

        // 通过数据源设置的变量
        $this->assign('selectList',$this->getSelectList());
        return $this->fetch('common/base_content_category_edit');
    }
    public function category_del(){
        $param = input('param.');
        $id = input('param.id');
        if(empty($id)){
            $this->error('请提交正确的参数');
        }
        $id = hashIdDecode($id);
        if (empty($id)){
            $this->error('参数错误',url('category'));
        }
        $categoryModelName = 'Category';
        $alj = new \app\common\logic\AdminLogic($categoryModelName);
        $jieguo = $alj->del($id);
        if($jieguo['err_code'] === 0){
            $this->success($jieguo['msg']);
        }else{
            $this -> error($jieguo['msg']);
        }
    }

    public function index(){
        $aorm = model($this->modelName);
        /**
         * 查询条件
         */
        $whereKeys = $aorm->getSearchFields();
        $cLogic = new \app\common\logic\ContentLogic();
        $alj = new \app\common\logic\AdminLogic($this->modelName);
        $listFields = $cLogic->_getModelsShowField($this->modelName,$this->modelId,'list');
        // 保持列表和搜索列表一致
        foreach ($whereKeys as $key => $field){
            if(!array_key_exists($key,$listFields)){
                unset($whereKeys[$key]);
            }
        }

        $paramWhere = $this->getParamWhere($whereKeys);
        $where[] = ['model_id','=',$this->modelId];
        $data = $cLogic->_getCategorySelectData($where);
        $this->addSelectList('catList',$data);
        $paramWhere['where'][] = ['model_id','=',$this->modelId];

        $pagerInfo = $this->getPagerInfo($alj->_getCountByWhere($paramWhere['where']),input('p',1),$paramWhere['search']);
        $dataList = $alj->_getListByWhere($paramWhere['where'],$pagerInfo['offset'],$pagerInfo['pageSize']);

        $this->assign('datas',$dataList);
        $this->assign('search',$paramWhere['search']);
        $this->assign('whereKeys',$whereKeys);
        $this->assign($pagerInfo);
        $this->assign('listFields',$listFields);
        $operationBtns = $aorm->getOperationBtns();
        $this->assign('operationBtns',$operationBtns);
        // 通过数据源设置的变量
        $this->assign('selectList',$this->getSelectList());

        return $this->fetch($this->templatePreFix . 'index');
    }

    //--------------------------------------------------------------------------------------

    public function handle_add_get(&$param){
        $cLogic = new \app\common\logic\ContentLogic();
        $where[] = ['model_id','=',$this->modelId];
        $data = $cLogic->_getCategorySelectData($where);
        $this->addSelectList('catList',$data);
        // 处理显示的列
        $formFields = $cLogic->_getModelsShowField($this->modelName,$this->modelId,'add');

        $this->assign('formFields',$formFields);
        return ['err_code' => 0 , 'msg' => '默认通过'];
    }

    public function handle_add_post_before(&$param){
        $param['model_id'] = $this->modelId;
        $param['aid'] = $this->adminId;
        return ['err_code' => 0 , 'msg' => '默认通过'];
    }

    /**
     * 添加 保存 后
     * @param $flag
     * @return array
     */
    public function handle_add_post_after(&$param,&$flag){
        // 没有错误的情况下，进行附加表操作
        if($flag['err_code'] < 1){
            $cLogic = new \app\common\logic\ContentLogic();
            if(false === $cLogic->_setExtendTableColumValue($this->modelName,$flag['data']['id'],$param,$this->modelId)){
                return ['err_code' => 1 , 'msg' => '附加表操作失败'];
            }
        }
        return ['err_code' => 0 , 'msg' => '默认通过'];
    }

    // --------------------------------- 编辑 -------------------------------------------------
    public function handle_edit_get_before(&$param){
        $cLogic = new \app\common\logic\ContentLogic();
        $where[] = ['model_id','=',$this->modelId];
        $data = $cLogic->_getCategorySelectData($where);
        $this->addSelectList('catList',$data);

        // 处理显示的列
        $formFields = $cLogic->_getModelsShowField($this->modelName,$this->modelId,'edit');

        $this->assign('formFields',$formFields);

        return ['err_code' => 0 , 'msg' => '默认通过'];
    }
    /**
     * 编辑 获取 model 后
     * @param $model
     */
    public function handle_edit_get_after(&$model){
        $cLogic = new \app\common\logic\ContentLogic();
        $id = hashIdDecode($model['id']);
        if (!empty($id)) {
            $ext = $cLogic->_getExtendTableColumValue($this->modelName,$id,$this->modelId);
        }
        else{
            $ext = $cLogic->_getExtendTableColumValue($this->modelName,$model['id'],$this->modelId);
        }
        $model = array_merge($model,$ext);
        return ['err_code' => 0 , 'msg' => '默认通过'];
    }
    public function handle_edit_post_before(&$param){
        $param['model_id'] = $this->modelId;
        $param['aid'] = $this->adminId;
        return ['err_code' => 0 , 'msg' => '默认通过'];
    }

    /**
     * 编辑后
     */
    public function handle_edit_post_after(&$param,$jieguo){
        // 没有错误的情况下，进行附加表操作
        if($jieguo['err_code'] < 1){
            $cLogic = new \app\common\logic\ContentLogic();
            if(false === $cLogic->_setExtendTableColumValue($this->modelName,$param['id'],$param,$this->modelId)){
                return ['err_code' => 1 , 'msg' => '附加表操作失败'];
            }
        }
        return ['err_code' => 0 , 'msg' => '默认通过'];
    }
}